<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false" draggable
    :width="width >= 600 ? 600 : '100%'" @before-ok="save" @close="reset">
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { useResetReactive } from '@/hooks'
import { useDict, useNickname, useTaskName } from '@/hooks/app'
import { addProjectInfo, getProjectInfo, updateProjectInfo } from '@/apis/task/projectInfo'
import { type Columns, GiForm, type Options } from '@/components/GiForm'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改项目' : '新增项目'))
const formRef = ref<InstanceType<typeof GiForm>>()

const { nicknameList, getNicknameList } = useNickname()

const options: Options = {
  form: { size: 'large' },
  btns: { hide: true },
}

const [form, resetForm] = useResetReactive({
  // todo 待补充
})

const columns: Columns = reactive([
  {
    label: '项目名称',
    field: 'name',
    type: 'input',
    rules: [{ required: true, message: '请输入项目名称' }]
  },
  {
    label: '项目简介',
    field: 'description',
    type: 'textarea',
    rules: [{ required: true, message: '请输入项目名称' }]
  },
  // {
  //   label: '开始时间',
  //   field: 'startTime',
  //   type: 'date-picker',
  //   props: {
  //     showTime: true,
  //   },
  //   rules: [{ required: true, message: '请输入开始时间' }]
  // },
  // {
  //   label: '结束时间',
  //   field: 'endTime',
  //   type: 'date-picker',
  //   props: {
  //     showTime: true,
  //   },
  //   rules: [{ required: true, message: '请输入结束时间' }]
  // },
  {
    label: '责任人',
    field: 'userId',
    type: 'select',
    options: nicknameList,
    props: {
      allowSearch: true,
    },
    rules: [{ required: true, message: '请选择责任人' }]
  },
])

// 重置
const reset = async () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
  if (!nicknameList.value.length) {
    await getNicknameList()
  }
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateProjectInfo(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addProjectInfo(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = async () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const { data } = await getProjectInfo(id)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
